var timer;
const APP = getApp()
const AUDIOMANAGER = getApp().globalData.global_bac_audio_manager.manage
const AUDIO = getApp().globalData.global_bac_audio_manager

Page({
  /**
   * 页面的初始数据
   */
  data: {
    song:'http://www.wgx0725.com/music2.mp3',
    autoplayArr:[{
      name: "开",
      value: true,
      active: true
    },{
      name: "关",
      value: false,
      active: false
    }],
    intervalArr:[{
      name: "5s",
      value: 5000,
      active: true
    },{
      name: "3s",
      value: 3000,
      active: false
    },{
      name: "7s",
      value: 7000,
      active: false
    },{
      name: "10s",
      value: 10000,
      active: false
    }],
    rotateArr:[{
      name: "原图",
      value: -90,
      active: true
    },{
      name: "左90°",
      value: 180,
      active:false
    },{
      name: "右90°",
      value: 0,
      active: false
    },{
      name: "180°",
      value: 90,
      active: false
    }], 
    flag:1,
    muban:0,
    navState:0,
    displayText: "手持弹幕",
    panelFlag: false,
    barFlag: true,
    rotateIndex:0,
    intervalIndex:0,
    autoplayIndex:0,
    backcolorIndex:0,
    colorIndex: 0,
    speedIndex: 0,
    sizeIndex: 0,
    fontIndex:0,
    scorllDuration: 500,
    textLen: 0,
    animation: {},
    currentSpeed: 0,
    images: [],
    is_play: 0,//是否播放音乐
    sizeArr: [{
      name: "24",
      value: 24,
      active: true
    },{
      name: "36",
      value: 36,
      active: false
    },{
      name: "48",
      value: 48,
      active: false
    },{
      name: "72",
      value: 72,
      active: false
    }],
    speedArr: [{
      name: "0.25x",
      value: 8000,
      active: true
    },{
      name: "0.5x",
      value: 7000,
      active: false
    },{
      name: "1x",
      value: 5000,
      active: false
    },{
      name: "1.5x",
      value: 4000,
      active: false
    },{
      name: "2x",
      value: 3000,
      active: false
    }],
    colorArr: [{
      value:'#FFFFFF',
      active:true
    },{
      value:'#00FF00',
      active:false
    },{
      value:'#FF0000',
      active:false
    },{
      value:'#FF1177',
      active:false
    },{
      value:'#FF00FF',
      active:false
    },{
      value:'#0000FF',
      active:false
    },{
      value:'#FFFF00',
      active:false
    },{
      value:'#00FFFF',
      active:false
    }
    ,{
      value:'#65318E',
      active:false
    },{
      value:'#1E50A2',
      active:false
    },{
      value:'#006E54',
      active:false
    }],
    backcolorArr: [{
      value:'#000000',
      active:true
    },{
      value:'#FFFFFF',
      active:false
    },{
      value:'#00FF00',
      active:false
    },{
      value:'#FF0000',
      active:false
    },{
      value:'#FF1177',
      active:false
    },{
      value:'#FF00FF',
      active:false
    },{
      value:'#0000FF',
      active:false
    },{
      value:'#FFFF00',
      active:false
    },{
      value:'#00FFFF',
      active:false
    }
    ,{
      value:'#65318E',
      active:false
    },{
      value:'#1E50A2',
      active:false
    },{
      value:'#006E54',
      active:false
    }],
    fontArr:[{
      value: "Microsoft YaHei",
      active: true
    },{
      value: "KaiTi",
      active: false
    },{
      value: 'LiHei Pro Medium',
      active: false
    },{
      value: "YouYuan",
      active: false
    },{
      value: "cursive",
      active: false
    }],

  },
  setMuban1:function() {
    this.setData({
      muban:4
    })
  },
  // 当关闭图片时可调节背景颜色
  setMuban:function() {
    this.setData({
      muban:0
    })
  },
  // 图片方向
  changeRotate: function(e) {
    var newIndex = parseInt(e.currentTarget.dataset.index),
      after = 'rotateArr[' + newIndex + '].active',
      before = 'rotateArr[' + this.data.rotateIndex + '].active';

    this.setData({
      rotateIndex: newIndex,
      [before]: false,
      [after]: true
    })
    this.textInput();
  },
  // 自动切换图片
  changeAutoplay: function(e) {
    var newIndex = parseInt(e.currentTarget.dataset.index),
      after = 'autoplayArr[' + newIndex + '].active',
      before = 'autoplayArr[' + this.data.autoplayIndex + '].active';

    this.setData({
      autoplayIndex: newIndex,
      [before]: false,
      [after]: true
    })
    this.textInput();
  },
  // 自动切换间隔
  changeInterval: function(e) {
    var newIndex = parseInt(e.currentTarget.dataset.index),
      after = 'intervalArr[' + newIndex + '].active',
      before = 'intervalArr[' + this.data.intervalIndex + '].active';

    this.setData({
      intervalIndex: newIndex,
      [before]: false,
      [after]: true
    })
    this.textInput();
  },
  //点击添加按钮选择图片
chooseImage:function (e) {
  wx.chooseImage({
    sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
    sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
    success: res => {
      const images = this.data.images.concat(res.tempFilePaths)
      this.setData({
        images: images,
        muban:4
      })
    }
  })
  this.textInput();
},
// 删除图片
removeImage(e) {
  const idx = e.target.dataset.idx;
  this.data.images.splice(idx, 1);
  var del_image = this.data.images;
  this.setData({
    images: del_image
  })
  // 如果背景图片数组为空则切换模板值为0
  if(this.data.images==0){
    this.setData({
      muban:0
    });
  }
},
// 查看大图
handleImagePreview(e) {
  const idx = e.target.dataset.idx
  const images = this.data.images
  wx.previewImage({
    current: images[idx], //当前预览的图片
    urls: images, //所有要预览的图片
  })

},
  //监听滑块
  bindchange(e) {
    // console.log(e.detail.current)
    let index = e.detail.current;
    this.setData({
      panelAmt: 0,
      panelFlag: true,
      barAmt: 100,
      barFlag: false,
      navState:index
    })
  },
  //点击导航
  navSwitch: function(e) {
    // console.log(e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index;
    this.setData({
      navState:index
    })
  },
  //模板
 muBan: function(e) {
    // console.log(e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index;
    this.setData({
      muban:index
    })
    this.textInput();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      windowHeight: wx.getSystemInfoSync().windowHeight
    })
    // 录音
    var that = this;
    this.recorderManager = wx.getRecorderManager();
    this.recorderManager.onError(function(){
      that.tip("录音失败！")
    });
    this.recorderManager.onStop(function(res){
      that.setData({
        src: res.tempFilePath 
      })
      console.log(res.tempFilePath )
      that.tip("录音完成！")
    });
    this.innerAudioContext = wx.createInnerAudioContext();
    // this.innerAudioContext.src =this.data.src;
    this.innerAudioContext.onError((res) => {
      that.tip("播放录音失败！")
    })

    // 背景音乐
    var that = this
    that.setData({
      is_loop: true,//是否循环播放
      is_play: false,//是否正在播放
    })
    AUDIOMANAGER.onPlay(() => {
      setTimeout(() => {
        that.setData({
          is_loading: true
        })
      }, 300)
    })
    let response = {
      urlCompressed: this.data.song,
      articleName: '测试音乐',
      lessonName: '专辑名',
      poster: 'http://www.1810.com.cn/static/uploadfile/file/2019-02-19/5c6bd0b57f8dc.jpg',
    }
    audio_background_play(response)
    // 背景音频播放完毕
    AUDIOMANAGER.onEnded(() => {
        // 单曲循环
        audio_background_play(response)
    })
  },
   /* 提示*/
   tip: function (msg) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false
    })
  },

  /*录制mp3音频*/
   startRecordMp3: function () {
    this.recorderManager.start({
      format: 'mp3'
    });
  },
  onSong:function(e){
    this.songValue = e.detail.value
  },
  // 上传歌曲
  uploadSong:function(){
    this.setData({
      song: this.songValue
    });
    let response = {
      urlCompressed: this.data.song,
      articleName: '测试音乐',
      lessonName: '专辑名',
      poster: 'http://www.1810.com.cn/static/uploadfile/file/2019-02-19/5c6bd0b57f8dc.jpg',
    }
    audio_background_play(response)
    // 背景音频播放完毕
    AUDIOMANAGER.onEnded(() => {
        // 单曲循环
        audio_background_play(response)
      })
      console.log(urlCompressed);
  },

  /* 停止录音*/
  stopRecord: function(){
    this.recorderManager.stop()
  }, 

  /*播放录音*/
 playRecord: function(){
    var that = this;
    var src = that.data.src;
    if (src == '') {
      this.tip("请先录音！")
      return;
    }
    this.innerAudioContext.src = that.data.src;
    this.innerAudioContext.loop=true
    this.innerAudioContext.play()
  },
  playStop:function(){
    this.innerAudioContext.stop()
  },
  /**
   * 查询字幕长度
   */
  getTextLen: function() {
    var query = wx.createSelectorQuery();
    query.select('.scorll-text').boundingClientRect((obj) => {
      this.setData({
        textLen: parseInt(obj.height)
      })
    }).exec();
  },
  /**
   * 清除字幕
   */
  clearScorll: function() {
    clearInterval(timer);
    this.data.animation.translate3d(0, 0, 0).step({
      duration: 0
    })
    this.setData({
      scorll: this.data.animation.export()
    })
  },
  // 改变字体样式
  changeFont:function(e) {
    var newIndex = parseInt(e.currentTarget.dataset.index),
     after = 'fontArr[' + newIndex + '].active',
     before = 'fontArr[' + this.data.fontIndex + '].active';
     this.setData({
       fontIndex: newIndex,
       [before]: false,
       [after]: true
      })
      const self = this
      wx.loadFontFace({
        family:  this.data.displayText,
        source:  fontArr[fontIndex ].source,
        success: console.log
      })
      this.textInput();
  },
  // 改变背景颜色
  changeBackColor: function(e) {
    var newIndex = parseInt(e.currentTarget.dataset.index),
      after = 'backcolorArr[' + newIndex + '].active',
      before = 'backcolorArr[' + this.data.backcolorIndex + '].active';

    this.setData({
      backcolorIndex: newIndex,
      [before]: false,
      [after]: true
    })
    this.textInput();
  },

  /**
   * 改变字体颜色
   */
  changeColor: function(e) {
    var newIndex = parseInt(e.currentTarget.dataset.index),
      after = 'colorArr[' + newIndex + '].active',
      before = 'colorArr[' + this.data.colorIndex + '].active';

    this.setData({
      colorIndex: newIndex,
      [before]: false,
      [after]: true
    })
    this.textInput();
  },

  /**
   * 改变速度
   */
  changeSpeed: function(e) {
    this.clearScorll()
    var newIndex = parseInt(e.currentTarget.dataset.index);
    var after = 'speedArr[' + newIndex + '].active',
      before = 'speedArr[' + this.data.speedIndex + '].active';
    this.setData({
      speedIndex: newIndex,
      currentSpeed: this.data.windowHeight * 2 / this.data.speedArr[newIndex].value,
      [before]: false,
      [after]: true
    })
    this.scorllFuc();
  },

  /**
   * 改变字体大小
   */
  changeSize: function(e) {
    this.clearScorll()
    // 先设置大小
    var newIndex = parseInt(e.currentTarget.dataset.index),
      currentLen = this.data.textLen,
      after = 'sizeArr[' + newIndex + '].active',
      before = 'sizeArr[' + this.data.sizeIndex + '].active';
    this.setData({
      sizeIndex: newIndex,
      [before]: false,
      [after]: true
    })

    // 刷新
    this.scorllFuc();
  },
  onInput:function(e){
    this.inputValue = e.detail.value
  },
  textInput: function() {
    this.clearScorll()
    this.setData({
      displayText: this.inputValue
    });
    this.scorllFuc();
  },
  /**
   * 动画控制
   */
  scorllFuc: function() {
    this.getTextLen();
    var scorllH = this.data.windowHeight * 2 + this.data.textLen;
    this.data.scorllDuration = parseInt(scorllH / this.data.currentSpeed);
    var scorllAmt = () => {
      this.data.animation.translate3d(-scorllH, 0, 0).step({
        duration: this.data.scorllDuration
      })
      this.data.animation.translate3d(0, 0, 0).step({
        duration: 0
      })
      this.setData({
        scorll: this.data.animation.export()
      })
    };
    scorllAmt();
    // 循环动画
    timer = setInterval(() => {
      scorllAmt();
    }, 
    this.data.scorllDuration + 500);
  },
  togglePanel: function() {
    const flag=this.data.flag
    if(flag){
      if (this.data.barFlag) {
        this.setData({
          barAmt: 100,
          barFlag: false,
        })
      } else {
        this.setData({
          barAmt: 0,
          barFlag: true,
        })
      }
      if (this.data.panelFlag) {
        this.setData({
          panelAmt: 100,
          panelFlag: false
        })
      } else {
        this.setData({
          panelAmt: 0,
          panelFlag: true
        })
      }
    }
    
  },
  toggleBar: function() {
    if (this.data.barFlag) {
      this.setData({
        barAmt: 100,
        barFlag: false,
        panelFlag: false,
        panelAmt: 100
      })
    } else {
      this.setData({
        barAmt: 0,
        barFlag: true,
        panelFlag: false,
        panelAmt: 100
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var animation = wx.createAnimation({
      timingFunction: 'linear'
    });
    this.data.animation = animation;

    //初始化速度
    this.data.currentSpeed = this.data.windowHeight * 2 / this.data.speedArr[this.data.speedIndex].value;

    this.scorllFuc();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})
// 音频播放
function audio_background_play(response) {
  AUDIOMANAGER.src = response.urlCompressed ? response.urlCompressed : response.audioLink // 音频的数据源，默认为空字符串，当设置了新的 src 时，会自动开始播放 ，目前支持的格式有 m4a, aac, mp3, wav
  AUDIOMANAGER.title = response.articleName // 音频标题
  AUDIOMANAGER.epname = response.lessonName // 专辑名
  AUDIOMANAGER.singer = '****' // 歌手名
  AUDIOMANAGER.coverImgUrl = response.poster // 封面图url
}